<script setup lang="ts">
import C2Scroll from './c2-scroll'
import ItemsContainer from './items-container-v2'
import { onShow, onLoad, onPageScroll, onShareAppMessage, onShareTimeline, onReachBottom } from '@dcloudio/uni-app'
import { defineProps } from 'vue';
import _ from 'lodash'
import useShare from '@/mixins/share';
import {
  getC2ListByC1IdV2,
  v2_pageGood
} from '@/api/search'
import { ref, reactive, nextTick } from 'vue'
import { shareUtils } from '@/utils/share'
import { useSettingStore } from '@/store/setting'
const { getShareCover } = useShare()
const bannerList = ref([])
const store = useSettingStore()
const loading = ref(true)
const props = defineProps({
  id: {
    type: String,
    default: ""
  },
  keyword: {
    type: String,
    default: ""
  },
  
})
const layout = ref('1')

onReachBottom(() => {
  // debugger
  handleOnLower()

})

onPageScroll(_.throttle((e) => {
  scrollTop.value = e.scrollTop
}, 100))

let queryWrapper = reactive({
  c1Id: undefined,
  c2Id: undefined,
  c3Id: undefined,
  c2SecondName: undefined,
  c3SecondName: undefined,
  pageSize: 10,
  pageNumber: 1,
  keyword: ''
})
const c2List = ref([])

const goodList = ref([])
const totalPage = ref(0)

const page = getCurrentPages().pop()

let path: string = page.route

// debugger
const init_scroll_top_h = ref(0)

onShareAppMessage(() => {


  const share_path = `${path}?id=${queryWrapper.c1Id}&c2Id=${queryWrapper.c2Id}&keyword=${queryWrapper.keyword}&layout=${layout.value}`

  let t_array = [];

  if (catalog_title.value) {
    t_array.push(catalog_title.value)
  }

  if (catalog_c2_title.value) {
    t_array.push(catalog_c2_title.value)
  }

  if (queryWrapper.keyword) {
    t_array.push(queryWrapper.keyword)
  }


  let title = t_array.join('#');



  const promise = new Promise(resolve => {


    getShareCover(`${path}?id=${queryWrapper.c1Id}`, title, null).then(res => {


      res.path = shareUtils.buildPathQuery(share_path)
      resolve(res)
    })

  })

  return {
    title,
    path: shareUtils.buildPathQuery(share_path),
    promise
  }
})

onShareTimeline(() => {


  const share_path = `${path}?id=${queryWrapper.c1Id}&c2Id=${queryWrapper.c2Id}&keyword=${queryWrapper.keyword}&layout=${layout.value}`

  let t_array = [];

  if (catalog_title.value) {
    t_array.push(catalog_title.value)
  }

  if (catalog_c2_title.value) {
    t_array.push(catalog_c2_title.value)
  }

  if (queryWrapper.keyword) {
    t_array.push(queryWrapper.keyword)
  }


  let title = t_array.join('#');



  const promise = new Promise(resolve => {


    getShareCover(`${path}?id=${queryWrapper.c1Id}`, title, null).then(res => {


      res.path = shareUtils.buildPathQuery(share_path)
      resolve(res)
    })

  })

  return {
    title,
    path: shareUtils.buildPathQuery(share_path),
    promise
  }
})

const option_c2Id = ref(null)

onLoad((options) => {


  queryWrapper.c1Id = options.id
  queryWrapper.pageNumber = options.pageNumber ? options.pageNumber : 1
  queryWrapper.pageSize = options.pageSize ? options.pageSize : 10
  queryWrapper.keyword = options.keyword ? options.keyword : ''
  queryWrapper.c2SecondName = options.c2SecondName
  queryWrapper.c3SecondName = options.c3SecondName
  debugger
  layout.value = options.layout ?? '1'
  //for loading from AppMessageShare 

  store.initSettingListByStore().then(res => {


    const query = wx.createSelectorQuery()

    query.select('#top').boundingClientRect()
      .exec(res => {
        // debugger
        init_scroll_top_h.value = res[0].height
      })
  })

  if (options.c2Id) {
    option_c2Id.value = options.c2Id
  }
  if (queryWrapper.c1Id) {
    init().then(() => {
      if (options.c2Id) {
        queryWrapper.c3Id = options.c3Id
        queryWrapper.c2Id = options.c2Id
        refreshData()
      }

    })
  }



})
const show_flag = ref(0)
onShow(() => {
  loading === true && init()
})

const catalog_title = ref('')
const catalog_c2_title = ref('')
const scrollTop = ref(-1)

const init = () => {
  loading.value = true

  return getC2ListByC1IdV2(queryWrapper.c1Id)
    .then((r) => {
    // debugger
      bannerList.value = r.banner.map(el=>el.url)
      loading.value = false
      catalog_title.value = r.title
      c2List.value = r.children.map(el => {
        el.name = el.title
        return el
      })

      return handleC2Tap(c2List.value[0])
      status.value = 'loading'
      //do not update the c1Id
      return v2_pageGood(queryWrapper)
    })
    .catch((e) => {
      console.error(e)
      status.value = 'loadmore'
    })
    .finally(() => {
      nextTick(() => {
        loading.value = false
      })
    })
}

const onScrollTopUpdate = (top) => {
  console.log(top)
}


const handleC2Tap = async (c2) => {
  // debugger
  if (loading.value) {
    return
  }

  const c2Id = c2.id
  catalog_c2_title.value = c2.title




  loading.value = true
  // 一些初始化的操作
  goodList.value = []
  totalPage.value = 0

  if (show_flag.value > 0) {
    wx.pageScrollTo({
      scrollTop: init_scroll_top_h.value - 70,
    })
  }

  show_flag.value += 1

  queryWrapper.c2Id = c2Id
  queryWrapper.c2SecondName = c2.name
  queryWrapper.pageNumber = 1
  status.value = 'loading'
  try {
    let { pageInfo, items } = await v2_pageGood(queryWrapper)
    goodList.value = items
    totalPage.value = pageInfo.totalPage
    if (queryWrapper.pageNumber >= totalPage.value) {
      status.value = 'nomore'
    }
  } catch (e) {
    console.error(e)
  } finally {
    nextTick(() => {
      loading.value = false
    })

  }
}

const sysInfo = ref({
  deviceModel: ''
})
uni.getSystemInfo().then(systemInfo => {

  sysInfo.value = systemInfo

  console.log(systemInfo)
})

let status = ref('loadmore')

const handleOnLower = async () => {
  // debugger
  if (queryWrapper.pageNumber >= totalPage.value) {
    return
  }

  if (loading.value) {
    return
  }
  status.value = 'loading'

  loading.value = true
  queryWrapper.pageNumber++
  let { pageInfo, items } = await v2_pageGood(queryWrapper)
  goodList.value = goodList.value.concat(items)
  totalPage.value = pageInfo.totalPage
  if (queryWrapper.pageNumber >= totalPage.value) {
    status.value = 'nomore'
  }
  nextTick(() => {
    loading.value = false
  })
}

const refreshData = async () => {
  if (loading.value) {
    return
  }


  status.value = 'loading'

  loading.value = true

  let { pageInfo, items } = await v2_pageGood(queryWrapper)
  goodList.value = items
  totalPage.value = pageInfo.totalPage
  if (queryWrapper.pageNumber >= totalPage.value) {
    status.value = 'nomore'
  }
  nextTick(() => {
    loading.value = false
  })
}

const handleSearch = () => {
  uni.navigateTo({
    url: `/pages/search/search`
  })
}
</script>

<template>
  <ForOneHeader2 @gosearch="handleSearch" :enableBack="true" />

  <view class="top" id="top">

    <u-swiper height="850rpx" indicator keyName="image" circular class="index-swiper" :list="bannerList"></u-swiper>
  </view>


  <u-sticky customNavHeight="130rpx" offsetTop="0" zIndex="10">


    <view class="main-scroll-container">
      <scroll-view class="scroll-1 scroll" scroll-y :scroll-with-animation="true">
        <C2Scroll class="c2-scroll" :deviceModel="sysInfo.deviceModel" :c2List="c2List" :c2Id="queryWrapper.c2Id"
          @do="handleC2Tap" />
      </scroll-view>
      <view :class="['main-scroll-mask']" style="background-color: transparent;">

      </view>

    </view>


  </u-sticky>

  <view class="x-layout">
    <view class="x-pad"></view>
    <view :class="['bottom-x']">

      <view class="unit">

        <view class="item-wrapper">
          <ItemsContainer :status="status" :scrollTop="scrollTop" :layout="layout" @on-lower="handleOnLower"
            :itemList="goodList" />
        </view>
      </view>
    </view>

  </view>
  <!-- <view class="flex-container-1">
   
    <u-swiper indicator keyName="image" circular class="index-swiper" :list="['']" @click="onclick"
      height="850rpx">
    </u-swiper>
    <view class="search-container">
      <view class="input-container">
        <u-search height="70rpx" :showAction="false" :clearabled="true" placeholder="请输入产品名称/型号"
          v-model="queryWrapper.keyword" @search="handleSearch"></u-search>
      </view>
      <view class="mid-row">
        <C2Scroll class="c2-scroll" :c2List="c2List" :c2Id="queryWrapper.c2Id" @do="handleC2Tap" />
        <view class="right">
          
          <ItemsContainer :status="status" :layout="props.layout" @on-lower="handleOnLower" class="items-container" :itemList="goodList" />
        </view>
      </view>
    </view> -->
  <!-- </view> -->
</template>

<style lang="scss" scoped>
@import '@/pages/grilles/common.scss';

.flex-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}


.mid-c2-scroll {
  width: 180rpx;
}

.unit {
  padding: 20rpx 0;
}
</style>
